package Wix::Tag;

use Carp;
use XML::Element;
use XML::Parser::PerlSAX;
use XML::Handler::YAWriter;
use Win32::Guidgen;

use strict;

sub new($) {
	my ($class, $args) = @_;
	
	my $element = XML::Element->new($args->{TAG});
	
	my $self = {
		_ELEMENT => $element
	};
	
	return bless($self, $class);
}

sub getElement() {
	my ($self) = @_;
		
	return $self->{_ELEMENT};
}

sub addElement($$) {
	my ($self, $element_type, $new_element) = @_;

	if (ref $new_element eq $element_type) {
		$self->getElement()->push_content($new_element->getElement());	
	}	
	else {
		carp sprintf('The provided element (%s) is not of the correct type: "%s"', ref $new_element, $element_type)	
	}
}

sub addAttr($$) {
	my ($self, $key, $value) = @_;
	
	if ($key eq 'Id') {
		$value =~ s/\s//g;
	}
	
	$self->getElement()->attr($key, $value) if $value; 
}

sub getAttr($) {
	my ($self, $key) = @_;
	
	$self->getElement()->attr($key) if $key; 
}

sub getSource() {
	my ($self) = @_;
	
	my $handler = XML::Handler::YAWriter->new(
		AsString => 1,
		Pretty => {
			NoWhiteSpace => 1,
			PrettyWhiteIndent => 1,
			PrettyWhiteNewline => 1,
			CatchEmptyElement => 1,
			CompactAttrIndent => 1
		}
	);
	
	my $parser = XML::Parser::PerlSAX->new(
		Handler => $handler
	);
	
	$parser->parse($self->{_ELEMENT}->as_XML);
	
	return join ('', @{$handler->{Strings}});
}

sub addGUID($) {
	my ($self, $attr) = @_;
		
	my $guid = Win32::Guidgen::create();
	
	$guid =~ s/^{(.+)}$/$1/;
	
	$self->getElement()->attr($attr, $guid);
}

1;